/**
 * Definition for singly-linked list.
 *  
 */
struct ListNode {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};


class Solution {
public:
    // 头插法 | 穿针引线
    ListNode* reverseBetween(ListNode* head, int left, int right) {
        // 设置 dummy node 是这类问题的一般做法
        ListNode* dummy = new ListNode(-1);  // 方便 left = 1 的情况
        dummy->next = head;

        ListNode* prev = dummy;
        for (int i=0; i<left-1; ++i) prev = prev->next;  // 到达区域外左边
        ListNode* curr = prev->next;
        ListNode* next;
        
        for (int i=0; i<right-left; ++i) {
            next = curr->next;
            curr->next = next->next;
            next->next = prev->next;
            prev->next = next;
        }
        return dummy->next;
    }
};
